﻿using Common;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;

namespace Web.Hanlder
{
    public class GoodsHandler : IHttpHandler
    {
        #region Base
        HttpRequest Request;
        HttpResponse Response;
        System.Web.SessionState.HttpSessionState Session;
        HttpServerUtility Server;
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            Request = context.Request;
            Response = context.Response;
            Session = context.Session;
            Server = context.Server;
            string method = Request["Method"].ToString();
            System.Reflection.MethodInfo methodInfo = this.GetType().GetMethod(method);
            methodInfo.Invoke(this, null);
        }
        public List<Model.tb_goods> GetOBJList()
        {
            return Common.SqlExption.GetList<Model.tb_goods>();
        }

        public void AddCart() {
            ReturnHelper<DBNull> rh = new ReturnHelper<DBNull>();
            int Id = Convert.ToInt32(Request["Id"]);
            if (!int.TryParse(Request["Id"], out Id))
            {
                if (Id <= 0)
                {
                    rh.states = 1;
                    rh.msg = " 请选择商品！";
                    string json = JsonConvert.SerializeObject(rh);
                    Response.Write(json);
                    Response.End();
                }
            }
            if (string.IsNullOrEmpty(Common.UICookie.ReadCookie("ClientUId")))
            {
                rh.states = 1;
                rh.msg = " 请先登录！";
                string json = JsonConvert.SerializeObject(rh);
                Response.Write(json);
                Response.End();
            }
            int cid = Convert.ToInt32(Common.UICookie.ReadCookie("ClientUId"));

            var goodes = Common.SqlExption.GetList<Model.tb_goods>().FirstOrDefault(c => c.Id.Equals(Id));
            if (goodes==null)
            {
                rh.states = 1;
                    rh.msg = " 商品不存在！";
                    string json = JsonConvert.SerializeObject(rh);
                    Response.Write(json);
                    Response.End();
            }
          string newId = string.Empty;
            Model.tb_order data = Common.SqlExption.GetList<Model.tb_order>().OrderByDescending(c => c.Id).FirstOrDefault();
            if (data != null)
            {
                newId = DateTime.Now.ToString("yyyyMMdd") + "00" + (Convert.ToInt32(data.Id) + 1).ToString();
            }
            else
            {
                newId = DateTime.Now.ToString("yyyyMMdd") + "00" + (0 + 1).ToString();
            }

            Model.tb_order model = new Model.tb_order() { 
             buy_nums=1,
              buy_prices=goodes.prices,
               create_time=DateTime.Now,
             order_number = newId,
              gid=goodes.Id,
               status=1,
                uid=cid

            };
            Common.SqlExption.Add(model);
            rh.states = 0;
            
            string scjson = JsonConvert.SerializeObject(rh);
            Response.Write(scjson);
            Response.End();
        }
        public void GetList()
        {
            var data = Common.SqlExption.GetList<Model.tb_goods>().AsQueryable();
            if (Request["goods_number"] != null)
            {
                string txt_search = Request["goods_number"];
                data = data.Where(c => c.goods_number.Contains(txt_search));
            }
            if (Request["name"] != null)
            {
                string txt_search = Request["name"];
                data = data.Where(c => c.name.Contains(txt_search));
            }
            if (Request["imgpath"] != null)
            {
                string txt_search = Request["imgpath"];
                data = data.Where(c => c.imgpath.Contains(txt_search));
            }
            string result = JsonConvert.SerializeObject(data.ToList());
            Response.Write(result);
            Response.End();

        }
        public void Del()
        {
            ReturnHelper<DBNull> rh = new ReturnHelper<DBNull>();
            int Id = int.Parse(Request["Id"]);

            var model = GetOBJList().FirstOrDefault(c => c.Id.Equals(Id));
            if (model != null)
            {
                Common.SqlExption.Delete<Model.tb_goods>(Id);
            }
            rh.states = 0;
            string jsonSucess = JsonConvert.SerializeObject(rh);

            Response.Write(jsonSucess);
            Response.End();
        }
        public void Edit()
        {


            ReturnHelper<DBNull> rh = new ReturnHelper<DBNull>();
            int Id = Convert.ToInt32(Request["Id"]);
            if (!int.TryParse(Request["Id"], out Id))
            {
                if (Id < 0)
                {
                    rh.states = 1;
                    rh.msg = " 验证错误！";
                    string json = JsonConvert.SerializeObject(rh);
                    Response.Write(json);
                    Response.End();
                }
            }
            var goods_number = Request["goods_number"];
            if (goods_number.Trim().Length <= 0)
            {
                rh.states = 1;
                rh.msg = "商品编号验证错误！";
                string json = JsonConvert.SerializeObject(rh);
                Response.Write(json);
                Response.End();
            }
            int goods_type = Convert.ToInt32(Request["goods_type"]);
            if (!int.TryParse(Request["goods_type"], out goods_type))
            {
                if (goods_type < 0)
                {
                    rh.states = 1;
                    rh.msg = "商品类型验证错误！";
                    string json = JsonConvert.SerializeObject(rh);
                    Response.Write(json);
                    Response.End();
                }
            }
            int goods_nums = Convert.ToInt32(Request["goods_nums"]);
            if (!int.TryParse(Request["goods_nums"], out goods_nums))
            {
                if (goods_nums < 0)
                {
                    rh.states = 1;
                    rh.msg = "商品库存验证错误！";
                    string json = JsonConvert.SerializeObject(rh);
                    Response.Write(json);
                    Response.End();
                }
            }
            decimal prices = Convert.ToDecimal(Request["prices"]);
            if (!decimal.TryParse(Request["prices"], out prices))
            {
                if (prices < 0)
                {
                    rh.states = 1;
                    rh.msg = "商品售价验证错误！";
                    string json = JsonConvert.SerializeObject(rh);
                    Response.Write(json);
                    Response.End();
                }
            }
            int sellnums = Convert.ToInt32(Request["sellnums"]);
            if (!int.TryParse(Request["sellnums"], out sellnums))
            {
                if (sellnums < 0)
                {
                    rh.states = 1;
                    rh.msg = "销量验证错误！";
                    string json = JsonConvert.SerializeObject(rh);
                    Response.Write(json);
                    Response.End();
                }
            }
            int Hot = Convert.ToInt32(Request["Hot"]);
            if (!int.TryParse(Request["Hot"], out Hot))
            {
                if (Hot < 0)
                {
                    rh.states = 1;
                    rh.msg = "商品热门错误！";
                    string json = JsonConvert.SerializeObject(rh);
                    Response.Write(json);
                    Response.End();
                }
            }
            int sellLevel = Convert.ToInt32(Request["sellLevel"]);
            if (!int.TryParse(Request["sellLevel"], out sellLevel))
            {
                if (sellLevel < 0)
                {
                    rh.states = 1;
                    rh.msg = "首页排序优先度验证错误！";
                    string json = JsonConvert.SerializeObject(rh);
                    Response.Write(json);
                    Response.End();
                }
            }
            var name = Request["name"];
            if (name.Trim().Length <= 0)
            {
                rh.states = 1;
                rh.msg = "名称验证错误！";
                string json = JsonConvert.SerializeObject(rh);
                Response.Write(json);
                Response.End();
            }
            var imgpath =string.Empty;
            var fs = Request.Files["imgpath"];
          
            if (fs != null)
            {
                if (fs.ContentLength <= 0)
                {
                    return;
                }
                string fileDianHua = Path.GetFileName(fs.FileName);
                string fileExt = Path.GetExtension(fileDianHua);
                string imageDir = "/ImageFile/" + DateTime.Now.Year + "/" + DateTime.Now.Month + "/" + DateTime.Now.Day + "/";
                Directory.CreateDirectory(Path.GetDirectoryName(Request.MapPath(imageDir)));//创建存储图片的目录;
                string newFileDianHua = DateTime.Now.ToString("yyyyMMddHHmmss");//使用GUID作为文件的新名称，当然也可以使用其他的方式对文件进行重命名。
                string fullDir = imageDir + newFileDianHua + fileExt;//完整的图片存储的路径
                string p = Server.MapPath(fullDir);

                imgpath = fullDir;
                fs.SaveAs(p);
            }

            var model = Common.SqlExption.GetList<Model.tb_goods>().FirstOrDefault(c => c.Id.Equals(Id));
            if (model == null)
            {
                model = new Model.tb_goods();
                model.Id = Id;
                model.goods_number = goods_number;
                model.goods_type = goods_type;
                model.prices = prices;
                model.sellnums = sellnums;
                model.sellLevel = sellLevel;
                model.name = name;
                model.goods_nums = goods_nums;
                model.Hot = Hot;
                if (!string.IsNullOrEmpty(imgpath))
                {
                    model.imgpath = imgpath;
                }

                Common.SqlExption.Add(model);
            }
            else
            {
                model.Id = Id;
                model.goods_number = goods_number;
                model.goods_type = goods_type;
                model.prices = prices;
                model.sellnums = sellnums;
                model.sellLevel = sellLevel;
                model.name = name;
                model.goods_nums = goods_nums;
                model.Hot = Hot;
                if (!string.IsNullOrEmpty(imgpath))
                {
                    model.imgpath = imgpath;
                }

                Common.SqlExption.Update(model);
            }
            rh.states = 0;
            string jsonSucess = JsonConvert.SerializeObject(rh);

            Response.Write(jsonSucess);
            Response.End();

        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
        #endregion
    }
}
